var form = layui.form, laydate = layui.laydate, annexList = [], upload = layui.upload, table = layui.table, $ = layui.jquery,
    id = getQueryVariable("id");
layui.use(['tableEdit'], function () {
    let  tableEdit = layui.tableEdit;
    let layer = layui.layer;
    let warehouseNamedData = [];
    let warehouseList = [];
    let personList = [];

    let detailData = [];
    layer.ready(function () {
        //获取详情信息
        $.ajax({
            type:"POST",
            dataType:"json",
            contentType: 'application/json',
            data:JSON.stringify(id),
            url:"planInStore/update",
            success:function(res){
                if(res.status == 200){
                    //主表信息赋值
                    $("#id").val(res.data.id);
                    $("#billNo").val(res.data.billNo);
                    $("#newBillNo").val(res.data.billNo);
                    $("#createDate").val(res.data.createTime);
                    $("#founder").val(res.data.operator);
                    getOutStockInfo(res.data.personNo);
                    $("#person").val(res.data.person);
                    getWarehouseId(res.data.warehouseId);
                    $("#warehouseName").val(res.data.warehouseName);
                    $("#memo").val(res.data.memo);

                    //产品列表信息
                    detailData = res.data.detailList;

                    //附件信息
                    annexList = res.data.annexVos;

                    table.reload('storageproductstableid',{data : detailData});
                    table.reload('attachmenttableid',{data : annexList});

                    return false;
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
            }
        });

    })
    form.render('select');
    laydate.render({
        elem: '#cdate'
    });

    //获取入库人信息
    function getOutStockInfo(code){
        $.ajax({
            url:"otherOutStock/getAllUserInfo",
            success:function(data){
                if(data.status == 200){
                    personList = data.data;
                    for(let i in data.data){
                        $('#personNo').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    $('#personNo').val(code);
                    form.render('select');
                }
            }
        });
    }

    //获取仓库信息
    function getWarehouseId(warehouseId) {
        //获取仓库信息
        $.ajax({
            url:"transfer/getWarehouse",
            async:false,
            success:function(data){
                if(data.status == 200){
                    warehouseList = data.data;
                    for(let i in data.data){
                        let temp = {
                            name : data.data[i].code,
                            value : data.data[i].name
                        };
                        warehouseNamedData.push(temp);
                        $('#warehouseNamedData').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    $('#warehouseNamedData').val(warehouseId);
                    form.render('select');
                }
            }
        });
    }

    //表单初始值，修改时调用
    if (id != "") {
        form.val("editor-form", {
            "receiptno": "入库单号",
        })
    }

    //监听入库人下拉框
    form.on('select(personNo)', function (data) {
        if(data.value === ""){
            return;
        }
        let name = getPersonNameByCode(data.value);
        $("#person").val(name);
    })

    function getPersonNameByCode(code){
        for(let i in personList){
            if(personList[i].code = code){
                return personList[i].name;
            }
        }
        return "";
    }

    //监听下拉框
    form.on('select(warehouseNamedData)', function (data) {
        if(data.value === ""){
            return;
        }
        $("#warehouseName").val(getWarehouseName(warehouseNamedData, data.value));
        let oldTransferData =  table.cache["storageproductstableid"];
        if(oldTransferData.length > 0){
            for(let i in oldTransferData){
                oldTransferData[i].newWarehouseName = getWarehouseName(warehouseNamedData, data.value);
                oldTransferData[i].newWarehouseId = data.value;
            }
            table.reload('storageproductstableid',{data : oldTransferData});
        }else {
            return;
        }

    })

    //根据仓库id获取仓库名称
    function getWarehouseName(warehouseNamedData, id){
        if(warehouseNamedData.length > 0){
            for(let i in warehouseNamedData){
                if(warehouseNamedData[i].name == id){
                    return warehouseNamedData[i].value;
                }
            }
        }
    }


//监听提交
    form.on('submit(form-element)', function (data) {
        //向后台组装数据
        //获取头部表单数据
        let req = data.field;
        //获取附件数据
        let annexReqs = table.cache["attachmenttableid"];
        //获取库存表单信息数据
        let details = table.cache["storageproductstableid"];
        let indexsl = 0;
        if(details.length > 0){
            $.each(details, function (index, value) {
                if (typeof (details[index]["purchaseNo"]) == "undefined" || details[index]["purchaseNo"] == "") {
                    layer.msg("产品表第" + (index + 1) + "条批次无采购单号，请完善采购单号后保存！");
                    indexsl++;
                    return false;
                }else if(null == details[index].num || details[index].num <= 0){
                    layer.confirm("存在入库数量为零的记录，这些记录审批后不会生成相关记录，是否删除？",
                        confirmInfo(3,6),
                        function (index) {
                            let newData = deleteDetails(details);
                            table.reload('storageproductstableid',{data : newData});
                            layer.close(index);
                        });
                    return false;
                }
            });

        }

        req["annexList"] = annexReqs;
        req["details"] = details;
        let datas = JSON.stringify(req);
        if(indexsl == 0){
            $.ajax({
                type:"POST",
                dataType:"json",
                contentType: 'application/json',
                data:datas,
                url:"planInStore/add",
                success:function(res){
                    if(res.status == 200){
                        layer.msg("保存成功", {icon: 6});
                        setTimeout(function () {
                            //保存成功则刷新提交过来的界面 并关闭此页面
                            parent.detab("views/jsp/WarehouseManagement/goodswarehouse.jsp");
                            parent.intab("views/jsp/WarehouseManagement/goodswarehouse.jsp","备货入库")
                            parent.detab("views/jsp/WarehouseManagement/tpl/newupgoodswarehouse.jsp"+(id==''?'':'?id='+id));
                        },)
                        return false;
                    }else {
                        layer.msg(res.msg, {icon: 5});
                    }
                }
            });
        }
        return false;
    });

    //遍历删除数量为0的数据
    function deleteDetails(details){
        for(var j = 0; j < details.length; j++){
            if(details[j].num <= 0){
                details.splice(j, 1);
                j--;
            }
        }
        return details;
    }

//--入库产品信息
    let initData = [];
    let cols = table.render({
        elem: '#storageproducts',
        id: 'storageproductstableid',
        data: initData,
        toolbar: '#storageproductstoolbar',
        cols: [[
            //{field: 'productimg', title: '产品图片', width: 120, align: 'center', templet: '#imgTpl'},
            {field: 'contractTypeStr', width: 120, title: '合同类型', sort: true},
            {field: 'productCode', width: 120, title: '产品编码', sort: true},
            {field: 'specificationCode', width: 120, title: '规格编码', sort: true},
            {field: 'specificationExplanation', width: 120, title: '规格说明', sort: true},
            {field: 'referenceQuantity', width: 120, title: '参考数量', sort: true},
            {field: 'purchaseNo', width: 260, title: '采购单号', sort: true},
            {field: 'productUnit', width: 120, title: '单位', sort: true},
            {field: 'foreignCurrencyUnitPrice', width: 120, title: '外币单价', sort: true},
            {field: 'moneySubtotal', width: 120, title: '金额小计', sort: true},
            {field: 'instoreCost', width: 120, title: '成本单价', sort: true},
            {field: 'grossWeight', width: 120, title: '毛重', sort: true},
            {field: 'netWeight', width: 120, title: '净重', sort: true},
            {field: 'supplierName', width: 120, title: '供应商名称', sort: true},
            /*{field: 'warehouseName', width: 120, title: '仓库名称', sort: true},*/
            {field: 'reRecordingFee', width: 120, title: '补录费用', sort: true},
            {field: 'trayNumber', width: 120, title: '托盘入数', sort: true},
            {field: 'totalTray', width: 120, title: '总托盘', sort: true},
            {field: 'color', width: 120, title: '颜色', sort: true},
            {field: 'productCname', width: 120, title: '中文名称', sort: true},
            {field: 'productEname', width: 120, title: '英文名称', sort: true},
            {field: 'productCdesc', width: 120, title: '中文描述', sort: true},
            {field: 'productEdesc', width: 120, title: '英文描述', sort: true},
            {field: 'memo', width: 210, title: '备注', sort: true},
            {fixed: 'right', field: 'num', width: 80, title: '数量',event: 'number',"config":{"type":"input","verify":{"type":"number"}}},
            {fixed: 'right', field: 'lotNo', width: 350, title: '批次号', event: 'lotNo',"config":{"type":"input"}},
            {
                fixed: 'right',
                field: 'newWarehouseName',
                width: 120,
                title: '新仓库名称',
                event: 'newWarehouseName',
                config:{"type":"select","data":warehouseNamedData}
            },
            {fixed: 'right', title: '操作', width: 110, align: 'center', toolbar: '#storageproductseditor'}]],
        height: 380,
        page: false,
        limit: Number.MAX_VALUE,
        height: 380
        , done: function (res, curr, count) {
            hoverOpenImg();//显示大图
            $(warehouseNamedData).each(function (i) {
                var option = $('<option value="' + warehouseNamedData[i].code + '">' + warehouseNamedData[i].name + '</option>');
                $("select[name = 'warehousenametable']").append(option);
            })
            form.render('select');
        }
    }).config.cols;
    let aopTable = tableEdit.aopObj(cols); //获取一个aop对象
    aopTable.on('tool(storageproductstable)', function (obj) {
        let field = $(this).data('field');
        let data = obj.data;
        if (field === 'newWarehouseName') {
            obj.update({"newWarehouseName": obj.value.value});
            layer.msg("修改成功", {icon: 6});
        }else if(field === 'num'){
            if(!checkTransferQuantity(data.referenceQuantity, obj.value)){
                layer.msg("入库数量不能大于参考数量", {icon: 5});
                return;
            }
            obj.update({"num": obj.value});
            layer.msg("修改成功", {icon: 6});
        }else if(field === 'lotNo'){
            obj.update({"lotNo":obj.value})
            layer.msg("修改成功", {icon: 6});
        }
        if (obj.event === 'del') {
            layer.confirm('确认删除?',confirmInfo(3,5), function (index) {
                let oldData =  table.cache["storageproductstableid"];
                for (var i = 0; i < oldData.length; i++) {
                    if (oldData[i].stockId == data.stockId) {
                        oldData.splice(i, 1);
                        i--;
                        table.reload('storageproductstableid',{data : oldData});
                        break;
                    }
                }
                layer.msg("删除成功", {icon: 6});
                layer.close(index);
            });
        }
    });

    //数据校验
    //入库数量不能大于参考数量
    function checkTransferQuantity(referenceQuantity, num){
        if(num > referenceQuantity){
            return false;
        }
        return true;
    }

    table.on('toolbar(storageproductstable)', function (obj) {
        switch (obj.event) {
            case 'shipmentdetails':
                layer.open({
                    type: 2,
                    area:["80%","95%"],
                    content: 'views/jsp/WarehouseManagement/tpl/shipmentdetails.jsp'
                });
                break;
        };
    });

    function hoverOpenImg() {
        var img_show = null; // tips提示
        $("body").delegate("td img", "mouseover", function () {
            var img = "<img class='img_msg' src='" + $(this).attr('src') + "' style='width:130px;' />";
            img_show = layer.tips(img, this, {
                tips: [2, 'rgba(41,41,41,.5)']
                , area: ['160px']
            });
        });
        $("body").delegate("td img", "mouseout", function () {
            layer.close(img_show);
        });
    }

    //---附件
    table.render({
        elem: '#attachment'
        , data: annexList
        , toolbar: '#attachmenttoolbar'
        , cols: [[
            {field: 'fileName', title: '文件名', fixed: true}
            , {field: 'uploadTime', title: '上传日期', fixed: true}
            , {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'}
        ]]
        , id: 'attachmenttableid'
        , height: 380
        , page: true
        , done: function (res, index, upload) {
            let data = res.data;
            for(let i in data){
                let flag = true;
                for(let j in annexList){
                    if(data[i].id == annexList[j].id){
                        flag = false;
                        break;
                    }
                }
                if(flag){
                    annexList.push(data[i]);
                }
            }
        }
    });
    upload.render({
        elem: '#uploadfile'
        , url: 'transfer/uploadFile'
        , field: "uploadify"
        , accept: 'file'
        , multiple: true
        , auto: false
        , bindAction: '#testListAction'
        , choose: function (obj) {
            var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
            //读取本地文件
            obj.preview(function (index, file, result) {
                var tr = $(['<tr id="upload-' + index + '">'
                    , '<td>' + file.name + '</td>'
                    , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                    , '<td>等待上传</td>'
                    , '<td>'
                    , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                    , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                    , '</td>'
                    , '</tr>'].join(''));

                //单个重传
                tr.find('.demo-reload').on('click', function () {
                    obj.upload(index, file);
                });

                //删除
                tr.find('.demo-delete').on('click', function () {
                    delete files[index]; //删除对应的文件
                    tr.remove();
                    uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                });

                $("#uploadlist").append(tr);
            });
        }
        , parseData: function(res){
            return {
                "code": res.status,
                "count": res.total,
                "data": res.data
            };
        }
        , done: function (res, index, upload) {
            let data = res.data;
            for(var i in data){
                if (data[i].status) { //上传成功
                    annexList.push(data[i]);
                    var tr = $("#uploadlist").find('tr#upload-' + index)
                        , tds = tr.children();
                    tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                    tds.eq(3).html(''); //清空操作
                    return delete this.files[index]; //删除文件队列已经上传成功的文件
                }
                this.error(index, upload);
            }
        }
        , error: function (index, upload) {
            var tr = $("#uploadlist").find('tr#upload-' + index)
                , tds = tr.children();
            tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
            tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
        }
    });

    table.on('toolbar(attachmenttable)', function (obj) {
        switch (obj.event) {
            case 'uploadfile':
                $("#uploadlist").html(""); //清空上传列表数据
                layer.open({
                    type: 1,
                    title: "文件上传",
                    area: ['710px', '340px'],
                    content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                    , cancel: function (index, layero) {
                        table.reload('attachmenttableid', {data:annexList}); //点击关闭刷新表格
                    }
                });
                break;
        }
        ;
    });
    table.on('tool(attachmenttable)', function (obj) {
        let data = obj.data;
        if (obj.event === 'download') { //下载
            let xmlHttpRequest = new XMLHttpRequest();
            let url = "wjinfo/downloadfile2?filename=" + data.filePath;
            xmlHttpRequest.open('GET', url, true);
            //设置请求头
            xmlHttpRequest.setRequestHeader("Content-type", "application/json")
            xmlHttpRequest.responseType = "blob";
            xmlHttpRequest.send(null);

            xmlHttpRequest.onload = function() {
                let content = xmlHttpRequest.response;
                // 组装a标签
                let elink = document.createElement("a");

                //设置文件下载路径
                elink.download = decodeURIComponent(data.fileName);
                elink.style.display = "none";
                let blob = new Blob([content], { type: 'application/force-download' });

                //解决下载不存在文件的问题，根据blob大小判断
                if(blob.size==0){
                    layer.msg('服务器没找到此文件，请联系管理员!');
                }else{
                    elink.href = window.URL.createObjectURL(blob);
                    document.body.appendChild(elink);
                    elink.click();
                    document.body.removeChild(elink);
                }

            }
        } else if (obj.event === 'del') {
            layer.confirm('确认删除?',
                confirmInfo(3,5), function (index) {
                    obj.del();
                    let id = data.id;
                    for (var i = 0; i < annexList.length; i++) {
                        if (annexList[i].id == id) {
                            annexList.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
                            i--; // 如果不减，将漏掉一个元素
                            break;
                        }
                    }
                    layer.msg("删除成功", {icon: 6});
                    layer.close(index);
                    table.reload('attachmenttableid', {data:annexList}); //ajax删除成功之后刷新表格
                });
        }
    });

//---操作日志
    let logData = [];
    table.render({
        elem: '#otherwarehouselog'
        , data: logData
        , cols: [[
            {field: 'operationtype', title: '操作类型', fixed: true}
            , {field: 'theoperator', title: '操作员'}
            , {field: 'operationdate', title: '操作日期'}
            , {field: 'modifythecontent', title: '修改内容'}
        ]]
        , id: 'logtableid'
        , height: 380
        , limit: 30//显示的数量
        , page: true
    });

    //时间处理 初始赋值
    function getNowFormatDate() {
        let date = new Date();
        let separator = "-";
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        let currentDate = year + separator + month + separator + strDate;
        return currentDate;
    }
    let currentDate = getNowFormatDate();

    //创建时间
    laydate.render({
        elem: '#createDate',
        value: currentDate,
        min: currentDate,
        max: currentDate,
        btns: ['confirm']
    });

    //提示信息渲染
    function confirmInfo(icon, anim) {
        let data = {
            icon: icon,
            title: "提示",
            offset: "auto",
            skin: 'layui-layer-molv',
            anim: anim
        }
        return data;
    }
})